<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Service;

use App\Entity\Room;
use App\Entity\User;
use App\Provider\RoomManager;
use App\Provider\UserManager;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;
use Room\JoinRoomRequest;

class JoinRoomService
{
    protected LoggerInterface $logger;

    protected RoomManager $roomManager;

    protected UserManager $userManager;

    public function __construct(LoggerFactory $loggerFactory, RoomManager $roomManager, UserManager $userManager)
    {
        $this->logger = $loggerFactory->get('join_room');
        $this->roomManager = $roomManager;
        $this->userManager = $userManager;
    }

    public function joinRoom(JoinRoomRequest $joinRoomRequest, int $fd)
    {
        $roomId = $joinRoomRequest->getRid();
        $userId = $joinRoomRequest->getUserId();
        if ($this->roomManager->hasRoom($roomId)) {
            $room = $this->roomManager->getRoom($roomId);
        } else {
            $room = new Room();
            $room->setRoomId($roomId);
            $this->roomManager->addRoom($room);
        }
        $room->setUserFd($userId, $fd);
        if ($this->userManager->hasUser($userId)) {
            $user = $this->userManager->getUser($userId);
        } else {
            $user = new User();
            $user->setUserId($userId);
        }
        $user->setFd($fd);
        $this->userManager->setUser($user);
        return true;
    }
}
